package net.sourceforge.cath.aspects.pojo;



import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

import net.sourceforge.cath.context.Context;
import net.sourceforge.cath.context.LoggingUnit;
import net.sourceforge.cath.logging.Logger;


public abstract aspect TracerAspect {
	pointcut scope();
	
	ThreadMXBean threadMxBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
	Logger logger = Logger.getInstance();
	
	Object around(): scope(){
		LoggingUnit unit = new LoggingUnit();
		String transactionId="empty";
		String localTransactionId = "L"+String.valueOf(System.currentTimeMillis());
		transactionId=Context.getGlobalTransactionId();
		unit.setTransactionId(transactionId);
		unit.setLocalTransactionId(localTransactionId);
		unit.setStartTime(System.currentTimeMillis());
		unit.setStartCpuTime(threadMxBean.getCurrentThreadCpuTime());
		unit.setSignature(thisJoinPoint.getSignature());
		
		Context.push(unit);
		logger.startLocalTransaction(unit);
		
		try{
			return proceed();
		}finally{
			unit.setEndTime(System.currentTimeMillis());
			unit.setEndCpuTime(threadMxBean.getCurrentThreadCpuTime());
				
			logger.endLocalTransaction(unit);
			logger.flush();
			Context.pop();

		}// try
	}
}
